package model

import (
	"context"
	"database/sql"
	"fmt"
	"strings"
	"time"

	"github.com/zeromicro/go-zero/core/stores/builder"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"github.com/zeromicro/go-zero/core/stringx"
)

var (
	operationLogFieldNames          = builder.RawFieldNames(&OperationLog{}, true)
	operationLogRows                = strings.Join(operationLogFieldNames, ",")
	operationLogRowsExpectAutoSet   = strings.Join(stringx.Remove(operationLogFieldNames, "create_time", "update_time"), ",")
	operationLogRowsWithPlaceHolder = builder.PostgreSqlJoin(stringx.Remove(operationLogFieldNames, "id", "create_time", "update_time"))
)

type (
	OperationLogModel interface {
		Insert(ctx context.Context, data *OperationLog) (sql.Result, error)
		FindOne(ctx context.Context, id int64) (*OperationLog, error)
		Update(ctx context.Context, data *OperationLog) error
		Delete(ctx context.Context, id int64) error
	}

	defaultOperationLogModel struct {
		conn  sqlx.SqlConn
		table string
	}

	OperationLog struct {
		Id         int64     `db:"id"`
		Uid        int64     `db:"uid"`         // 用户id
		Url        string    `db:"url"`         // 请求地址
		Param      string    `db:"param"`       // 请求参数
		CreateTime time.Time `db:"create_time"` // 创建时间
	}
)

func NewOperationLogModel(conn sqlx.SqlConn) OperationLogModel {
	return &defaultOperationLogModel{
		conn:  conn,
		table: `"public"."operation_log"`,
	}
}

func (m *defaultOperationLogModel) Insert(ctx context.Context, data *OperationLog) (sql.Result, error) {
	query := fmt.Sprintf("insert into %s (%s) values ($1, $2, $3, $4)", m.table, operationLogRowsExpectAutoSet)
	ret, err := m.conn.ExecCtx(ctx, query, data.Id, data.Uid, data.Url, data.Param)
	return ret, err
}

func (m *defaultOperationLogModel) FindOne(ctx context.Context, id int64) (*OperationLog, error) {
	query := fmt.Sprintf("select %s from %s where id = $1 limit 1", operationLogRows, m.table)
	var resp OperationLog
	err := m.conn.QueryRowCtx(ctx, &resp, query, id)
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultOperationLogModel) Update(ctx context.Context, data *OperationLog) error {
	query := fmt.Sprintf("update %s set %s where id = $1", m.table, operationLogRowsWithPlaceHolder)
	_, err := m.conn.ExecCtx(ctx, query, data.Id, data.Uid, data.Url, data.Param)
	return err
}

func (m *defaultOperationLogModel) Delete(ctx context.Context, id int64) error {
	query := fmt.Sprintf("delete from %s where id = $1", m.table)
	_, err := m.conn.ExecCtx(ctx, query, id)
	return err
}
